#/usr/bin/python
import os
import fnmatch
import ftplib

CONFIG_FILE = '/var/tmp/secui/log_backup_sent.conf'
FILE_SENT = '/var/tmp/secui/log_backup_sent.txt'
FILE_SENT_TEMP = '/var/tmp/secui/log_backup_sent.new'
LOGDIR = '/var/log/secui'

#CONFIG_FILE = './log_backup_sent.conf'
#FILE_SENT = './log_backup_sent.txt'
#FILE_SENT_TEMP = './log_backup_sent.new'
#LOGDIR = '.'

def load_already_sent():
    file_hash = {}
    with file(FILE_SENT) as inFile:
        for line in inFile:
            file_name = line.strip()
            file_hash[file_name] = 'Loaded'
    return file_hash

def check_firewall_logs(sent_hash):
    send_list = []
    for fname in os.listdir(LOGDIR):
        if (fnmatch.fnmatch(fname, 'fw4_allow_*.log')
            or fnmatch.fnmatch(fname, 'fw4_allow_*.log.lzo')
            or fnmatch.fnmatch(fname, 'fw4_deny_*.log')
            or fnmatch.fnmatch(fname, 'fw4_deny_*.log.lzo')):
            if fname in sent_hash:
                sent_hash[fname] = 'Exist'
            else:
                sent_hash[fname] = 'Ready'
                send_list.append(fname)
    return send_list

def send_firewall_logs(configs, send_list, sent_hash):
    # setup FTP connection and login
    print "server_addr = %s, user = %s, passwd = %s, remotedir = %s" % (configs.server_addr, configs.user, configs.passwd, configs.remotedir)
    try:
        ftp = ftplib.FTP(configs.server_addr, configs.user, configs.passwd, timeout = 20)
    except ftplib.error_reply:
        return -1
    except ftplib.error_temp:
        return -2
    except ftplib.error_perm:
        return -3
    except ftplib.error_proto:
        return -4

    # directory exist check
    try:
        ftp.cwd(configs.remotedir)
    except:
        print "Directory doesnot exist!!" + configs.remotedir
        directory = configs.remotedir.split('/')

        for d in directory:
            if d != "":
                try:
                    ftp.cwd(d)
                except:
                    ftp.mkd(d)
                    ftp.cwd(d)
            else:
                ftp.cwd("/")

    for fname in send_list:
        filebasename = os.path.basename(fname)

        fileUp = open(fname, 'rb')
        res = ftp.storbinary('STOR ' + filebasename, fileUp)
        print "Uploading... "   + fname
        fileUp.close()

        if res.startswith("2"):
            sent_hash[fname] = 'Sent'
        else:
            sent_hash[fname] = 'Fail'

    ftp.quit()

def print_sent_hash(sent_hash):
    with file(FILE_SENT_TEMP, "w") as newfile:
        for item in sent_hash.iteritems():
            if item[1] == 'Loaded':
                # remove file from sent hash
                pass
            elif item[1] == 'Sent' or item[1] == 'Exist':
                print >>newfile, item[0]
            else:
                # retry later
                pass
            
            print "sent_hash[%s] = %s" % item
    
    os.rename(FILE_SENT_TEMP, FILE_SENT)

class CONFIG :
    def set_server(self, arg):
        self.server_addr = arg

    def set_user(self, arg):
        self.user = arg

    def set_passwd(self, arg):
        self.passwd = arg

    def set_remotedir(self, arg):
        self.remotedir = arg

    key_function = [
        ( "server=", set_server ),
        ( "user=", set_user ),
        ( "passwd=", set_passwd ),
        ( "remotedir=", set_remotedir ),
        ]
    def __init__(self):
        self.server_addr = '192.168.105.77'
        self.user = 'anonymous'
        self.passwd = 'hello, world'
        self.remotedir = '/'
        
    def load_file(self, filename):
        with file(filename) as confFile:
            for line in confFile:
                if line.startswith("#"):
                    pass # ignore it comment
                else:
                    for key, function in CONFIG.key_function:
                        if line.startswith(key):
                            function(self, line[len(key):].strip())

def main():
    configs = CONFIG()
    configs.load_file(CONFIG_FILE)
    sent_hash = load_already_sent()
    send_list = check_firewall_logs(sent_hash)
    send_firewall_logs(configs, send_list, sent_hash)
    print_sent_hash(sent_hash)

if __name__ == '__main__':
    main()
